<template>
    <div>
        <el-upload :class="{disabled:uploadDisabled}" :action="apiUrl" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :multiple="multiple" :file-list="uploadList" :limit="limit" :on-exceed="handleExceed" accept="image/png,image/jpeg,image/gif,image/jpg" :on-success="handleSuccess" :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
export default {
    props: {
        imgArr: {
            type: Array,
            default: () => {
                return [];
            }
        },
        multiple: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
        limit: {
            type: Number,
            default: () => {
                return 1;
            }
        },
    },
    data() {
        return {
            apiUrl: 'https://jsonplaceholder.typicode.com/posts/',
            dialogImageUrl: '',
            dialogVisible: false,
            uploadList: []
        };
    },
    computed: {

        uploadDisabled: function() {
            return this.uploadList.length >= this.limit
        },

    },
    methods: {
        // 图片删除
        handleRemove(file, fileList) {
            this.uploadList = fileList;
        },
        // 上传成功的方法
        handleSuccess(response, file, fileList) {
            this.uploadList = fileList;
        },
        // 打开大图
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 最大图片的限制
        handleExceed(files, fileList) {
            this.$message({
                message: '最多上传图片为' + this.limit + '张',
                type: 'warning'
            });
        },
        // 上传中图片大小的限制
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
    },
    mounted() {
        this.uploadList = this.imgArr;
    },
    watch: {
        uploadList(list) {
            this.$emit('updata', this.uploadList);
        }
    }
}

</script>
<style lang="less">
.el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    font-size: 14px;
}

.el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
    line-height: 30px;
    font-size: 14px;
}
.disabled .el-upload--picture-card {
    display: none;
}
</style>
